<template>
  <div>
    <van-nav-bar
  class="user"
  title="个人信息"
  left-arrow
  @click-left="$router.back()"
/>
   
        <input 
          type="file" 
          hidden 
          id="file"
          accept="image/*" 
          ref="file"
          @change="change"
          >
        <van-cell title="头像" center>
          <label for="file">
          <van-image
            width="50"
            height="50"
            round
            fit="cover"
             
            :src="userInfo.avatar" />

          </label>
        </van-cell>
  
        <van-cell title="昵称" is-link :to="{path:'/edit',query:{nickname:userInfo.nickname}}" :value="userInfo.nickname" />
        <van-cell title="性别" is-link @click="sexPickerShow = true" :value="userInfo.sex || '请选择性别'" />
        <van-popup
          v-model="sexPickerShow"
          position="bottom"   
        >
        <van-picker title="选择" show-toolbar @confirm="sexPickerConfirm"
          @cancel="sexPickerShow = false" :columns="sexColumns" />
        </van-popup>

        <van-cell title="生日" is-link @click="datePickerShow = true" :value="userInfo.birthday ||'请选择生日'" />
         <van-popup
          v-model="datePickerShow"
          position="bottom"   
        >
        <van-datetime-picker
         :value="userInfo.birthday?new Date(userInfo.birthday):new Date(2000,0,1)"
          type="date"
          title="选择年月日"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="datePickerConfirm"
          @cancel="datePickerShow = false"
        />
         </van-popup>
    <div style="margin: 16px;">
        <van-button block type="info" color='#07c160' native-type="submit" @click="submit">确定</van-button>
    </div>

    <div>
        <router-link to="/reg"></router-link>
    </div>

  </div>
</template>

<script>
import { Cell, CellGroup ,Form ,Uploader ,Image as VanImage ,} from 'vant';
import { mapActions } from 'vuex';
import {editUserInfo} from '../../api/user'
import sexPickerMixin from './sexPickerMixin'
import datePickerMixin from './datePickerMixin'
export default {
  name:'userInfo',
  data(){
    return{
      userInfo:{},
     
    }
  },
  mixins:[sexPickerMixin,datePickerMixin],
  mounted(){
    console.log(this.userInfo)
  },
  // keep-alive后 又增加了两个新的生命周期钩了
  //激活 
  activated(){
    let nickname = sessionStorage.getItem('nickname')
      if(nickname){
        this.userInfo.nickname = nickname
    }
  },
  watch:{
    //数据无污染  刷新后也能拿到
    '$store.state.userInfo':{
      immediate:true,  //初始化后 立即进行监听
      handler(n,o){
        this.userInfo = JSON.parse(JSON.stringify(n))
      }
    }
  },
  
  components:{
    [Cell.name]:Cell,
    [CellGroup.name]:CellGroup,
    [Form.name]:Form,
    [Uploader.name]:Uploader  ,
    [VanImage.name]:VanImage ,
  },
  methods: {
    ...mapActions(['upload']),
   
     async change(e){
      console.log();  //没有使用vant 封装vant的

      let file  = e.target.files[0]; //二进制
      // 前端预览  FileReader  base64
      // 2 URL.createObjectURL   前端预览方法一

      this.userInfo.file = file
      let fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = (e)=>{
        this.userInfo.avatar = e.target.result
      }
      
     },
     //submit
      async submit(){
        let {_id,nickname,avatar,file,sex='',birthday=''} = this.userInfo;

        if(file){
          let fileList = [{
            file,
          }]  //和vant上传组件形状一样
         let res = await this.upload(fileList)
          avatar = res[0]

        }
        editUserInfo({
          uid:_id,
          nickname,
          avatar,
          sex,
          birthday
        }).then(res=>{
          console.log(res)
          
          //改完数据 返回没同步
          this.$toast(res.msg)
          if(res.code == 0){
            // 通知服务器 已经改了数据
            //  本地的 xuex的数据还没改

            //方法1. 直接调接口  严谨但浪费
            // this.$store.dispatch('getUserInfo',localStorage.getItem('token'))
            //方法2.本地修改
            this.$store.commit('change',{
              key:'userInfo',
              value:{
               _id,
              nickname,
              avatar,
              sex,
              birthday
              }
            })
              setTimeout(v=>{
                this.$router.back()
              },500)
          }
        })
      }
    },
  }
</script>

<style>

</style>